//
//  JigSawButtonContainerView.m
//  JigSawKiosk
//
//  Created by Stulberg on 10-10-17.
//  Copyright 2010 FruitonLabs. All rights reserved.
//

#import "JigSawButtonContainerView.h"

//#import "defines.h"


extern int kNumberOfMovies ;
 
extern NSString* kGraphicsPath ;
extern NSString* kHotkeysImage ;

 


@interface JigSawButtonContainerView (Internal)
-(CGImageRef)CGImageNamed:(NSURL*)name;
@end


@implementation JigSawButtonContainerView

@synthesize rootLayer, hotKeyLayer, stripView ;

#pragma mark initalization
- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
		
    }
    return self;
}

- (id)initWithURLS:(NSRect)frame urls:(NSMutableArray*)urls {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
		urlArray = urls ;
		[self setupLayers] ;
		selectedStrip = 0 ; // we always start at the first set of previews
		isDisabled = FALSE ;
		//[self startStopPreviewsAtStrip] ;
		//[self startPreviews] ;
    }
    return self;
}

#pragma mark setup
- (void)drawRect:(NSRect)dirtyRect {
    // Drawing code here.
	[[NSColor clearColor] setFill];
    NSRectFill(dirtyRect);
}


// our delegate methods

- (void)setDelegate:(id)aDelegate {
	// not retained
	delegate = aDelegate;
}

- (void)delegatedMethod {
	[delegate buttonContainerCallback:self buttonNumber:buttonPressed] ;
}


-(void) setupLayers {
	rootLayer = [CALayer layer] ;
	rootLayer.backgroundColor = CGColorGetConstantColor(kCGColorClear) ;
	rootLayer.bounds = CGRectMake(0, 0, [self bounds].size.width, [self bounds].size.height) ;
	[self setLayer:rootLayer] ;
	
	//int numMovies = 3 ;
	//int counter = 0 ;
	
	float frameHeight = [rootLayer bounds].size.height*0.8 ;
	//float mWidth = (frameHeight*16)/9 ;
	//float spacing ;//= ([rootLayer bounds].size.width/[urlArray count]) ;
	
	//spacing = mWidth+(mWidth*0.045) ;
	
	CGRect aRect ;

	//
	aRect = CGRectMake(0, 0, [rootLayer bounds].size.width, frameHeight) ;
	stripView = [[JigSawButtonStripView alloc] initWithObjects:aRect urls:urlArray] ;
	[rootLayer addSublayer:stripView] ;
	[stripView setPosition:CGPointMake([rootLayer bounds].size.width/2, [rootLayer bounds].size.height*0.5)] ;
	//
	//
	aRect = CGRectMake(0, 0, [self bounds].size.width, 
					   [self bounds].size.height*0.2) ;

	NSString *Lpath = [NSString stringWithFormat:@"%@%@", kGraphicsPath, kHotkeysImage];
	NSURL *url   = [NSURL fileURLWithPath:Lpath];
	CGImageRef image = [self CGImageNamed:url] ; // get an image ref
	
	hotKeyLayer = [CALayer layer] ;
	hotKeyLayer.contents = (id) image ; // make simple layer this image
	hotKeyLayer.frame = aRect ;
	[rootLayer addSublayer:hotKeyLayer] ;
	
	//
	aRect = CGRectMake(0, 0, 
					   [self bounds].size.width*0.25, [self bounds].size.height*0.3) ;
	
	stripSelectLayer =  [[JigSawStripSelectLayer alloc] initWithObj:aRect] ;
	[stripSelectLayer setPosition:CGPointMake([rootLayer bounds].size.width/2, -[rootLayer bounds].size.height*0.25)] ;
	[rootLayer addSublayer:stripSelectLayer] ;
}

-(void) stopAllPreviews {
	[stripView stopAllPreviews] ;
}

-(void) startPreviews {
	[stripView startPreviews] ;
}

-(void) startStopPreviewsAtStrip {
	
	switch (selectedStrip) {
		case 0:

			[stripView stripNumber:0] ;
			break;
		case 1:
			
			[stripView stripNumber:1] ;
			break;
		case 2:
			
			[stripView stripNumber:2] ;
			break;
		default:
			break;
	}
	
	// wait just a bit before ending movies and goto end
	if ([stopMoviesAtStripsTimer isValid]) {
		[stopMoviesAtStripsTimer invalidate] ;
		stopMoviesAtStripsTimer = nil ;
		[stopMoviesAtStripsTimer release];
	}
	stopMoviesAtStripsTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0f]
							 interval: 0.1	 
							   target: self
							 selector: @selector(stopMoviesAtStripsTimerMethod:)
							 userInfo: nil
							  repeats: NO];
	[[NSRunLoop currentRunLoop] addTimer:stopMoviesAtStripsTimer forMode:NSDefaultRunLoopMode];
	
}

- (void) stopMoviesAtStripsTimerMethod:(NSTimer *)timer {
	switch (selectedStrip) {
		case 0:
			 if(kNumberOfMovies >= 4)[stripView stopPreviewAtIndex:3] ;
			 if(kNumberOfMovies >= 5)[stripView stopPreviewAtIndex:4] ;
			 if(kNumberOfMovies >= 6)[stripView stopPreviewAtIndex:5] ;
			 
			 if(kNumberOfMovies >= 7)[stripView stopPreviewAtIndex:6] ;
			 if(kNumberOfMovies >= 8)[stripView stopPreviewAtIndex:7] ;
			 if(kNumberOfMovies >= 9)[stripView stopPreviewAtIndex:8] ;
			 
			
			break;
		case 1:
			 if(kNumberOfMovies >= 1)[stripView stopPreviewAtIndex:0] ;
			 if(kNumberOfMovies >= 2)[stripView stopPreviewAtIndex:1] ;
			 if(kNumberOfMovies >= 3)[stripView stopPreviewAtIndex:2] ;
			 
			if(kNumberOfMovies >= 7)[stripView stopPreviewAtIndex:6] ;
			if(kNumberOfMovies >= 8)[stripView stopPreviewAtIndex:7] ;
			if(kNumberOfMovies >= 9)[stripView stopPreviewAtIndex:8] ;
			 
			break;
		case 2:
			
			if(kNumberOfMovies >= 1)[stripView stopPreviewAtIndex:0] ;
			if(kNumberOfMovies >= 2)[stripView stopPreviewAtIndex:1] ;
			if(kNumberOfMovies >= 3)[stripView stopPreviewAtIndex:2] ;
			 
			if(kNumberOfMovies >= 4)[stripView stopPreviewAtIndex:3] ;
			if(kNumberOfMovies >= 5)[stripView stopPreviewAtIndex:4] ;
			if(kNumberOfMovies >= 6)[stripView stopPreviewAtIndex:5] ;

			break;
		default:
			break;
	}
	
	
}

-(void) setIsDisabled:(BOOL) val {
	isDisabled = val ;
}

- (int) getSelectedStrip {
	return selectedStrip ;
}
#pragma mark mouseActions


- (void)mouseIn:(CGPoint)cgloc
{
	
	//if(kRotate) {
	
	int count = 0 ;
	for(JigSawMovieButton *jsBut in [stripView stripMovieButtonArray]) {
		if (count < kNumberOfMovies) {
			CGPoint convertedPoint = [rootLayer convertPoint:cgloc toLayer:stripView];
			if ([jsBut hitTest:convertedPoint]) {
				buttonPressed = count ;
				[self delegatedMethod] ;
				[stripView stopAllPreviews] ;
				isDisabled = TRUE ;
			}
		}
		count ++ ;
	}
	
	if(!isDisabled) {
		CGPoint convertedPoint = [rootLayer convertPoint:cgloc toLayer:stripSelectLayer];
		
		if ([[stripSelectLayer selectLayer1] hitTest:convertedPoint]) {
			[CATransaction begin] ;
			[CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration] ;
			[stripView setPosition:CGPointMake([rootLayer bounds].size.width/2, [rootLayer bounds].size.height*0.5)] ;
			[[stripSelectLayer selectLayer1] setBackgroundColor:CGColorCreateGenericGray(0.3, 1.0)] ;
			[[stripSelectLayer selectLayer2] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[[stripSelectLayer selectLayer3] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[CATransaction commit] ;
			selectedStrip = 0 ;
			[self startStopPreviewsAtStrip] ;
			
		}
		else if ([[stripSelectLayer selectLayer2] hitTest:convertedPoint]) {
			[CATransaction begin] ;
			[CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration] ;
			[stripView setPosition:CGPointMake((-[rootLayer bounds].size.width/2)*1.03, [rootLayer bounds].size.height*0.5)] ;
			[[stripSelectLayer selectLayer1] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[[stripSelectLayer selectLayer2] setBackgroundColor:CGColorCreateGenericGray(0.3, 1.0)] ;
			[[stripSelectLayer selectLayer3] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[CATransaction commit] ;
			selectedStrip = 1 ;
			[self startStopPreviewsAtStrip] ;
		}
		else if ([[stripSelectLayer selectLayer3] hitTest:convertedPoint]) {
			[CATransaction begin] ;
			[CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration] ;
			[stripView setPosition:CGPointMake((-[rootLayer bounds].size.width)*1.53, [rootLayer bounds].size.height*0.5)] ;
			[[stripSelectLayer selectLayer1] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[[stripSelectLayer selectLayer2] setBackgroundColor:CGColorCreateGenericGray(0.9, 1.0)] ;
			[[stripSelectLayer selectLayer3] setBackgroundColor:CGColorCreateGenericGray(0.3, 1.0)] ;
			[CATransaction commit] ;	
			selectedStrip = 2 ;
			[self startStopPreviewsAtStrip] ;
		}
	}
	//}
}
/*
- (void)mouseDown:(NSEvent *)event
{
	if(!kRotate) {
		NSPoint  loc = [self convertPoint: [event locationInWindow] fromView: nil];	
		CGPoint cgloc = NSPointToCGPoint(loc) ;
		//CGPoint randomPoint  = CGPointZero;
		int count = 0 ;
		for(JigSawMovieButton *jsBut in movieButtonArray) {
			if ([jsBut hitTest:cgloc]) {
				
				 [CATransaction begin] ;
				 [CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration] ;
				 jsBut.position = randomPoint ;
				 [CATransaction commit] ;
				 
				buttonPressed = count ;
				[self delegatedMethod] ;
				[self stopAllPreviews] ;
			}
			count ++ ;
		}
	}
}

*/

#pragma mark Image utility
//Return a CGImageRef from the specified image file in the app's bundle
-(CGImageRef)CGImageNamed:(NSURL*)name {
	CFURLRef url = (CFURLRef) name;//[[NSBundle mainBundle] URLForResource:@"miljo.png" withExtension:nil];
	CGImageSourceRef source = CGImageSourceCreateWithURL(url, NULL);
	CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
	CFRelease(source);
	return (CGImageRef)[NSMakeCollectable(image) autorelease];
}

#pragma mark cleanup
-(void) dealloc {
	[rootLayer release] ;
	//[movieButtonArray release] ;
	[hotKeyLayer release] ;
	[stripView release] ;
	[super dealloc] ;
}


@end
